<template>
  <view class="hanzi-stroke-container">
    <view class="stroke-image-wrapper">
      <image 
        :src="strokeGifUrl" 
        class="stroke-gif"
        mode="aspectFit"
        :lazy-load="false"
        @error="handleImageError"
      />
    </view>
    <view class="controls" v-if="showControls">
      <button class="control-btn" @click="reloadGif">重新播放</button>
    </view>
  </view>
</template>

<script>
import { defineComponent } from "vue";
import { hanziApi } from '../api/hanzi.js';

export default defineComponent({
  name: 'HanziStrokeCanvas',
  props: {
    character: {
      type: String,
      required: true,
      default: '一'
    },
    autoPlay: {
      type: Boolean,
      default: true
    },
    showControls: {
      type: Boolean,
      default: true
    }
  },
  data() {
    return {
      strokeGifUrl: '',
      hasError: false,
      isLoading: true,
      timestamp: Date.now() // 用于强制刷新GIF
    }
  },
  watch: {
    character: {
      immediate: true,
      handler(newVal) {
        if (newVal && newVal !== '') {
          this.loadGif(newVal);
        }
      }
    }
  },
  methods: {
    async loadGif(char) {
      console.log('加载汉字笔顺GIF:', char);
      this.isLoading = true;
      this.hasError = false;
      
      try {
        // 获取汉字信息
        const response = await hanziApi.getCharacterStrokeGifUrl(char);
        if (response.statusCode === 200 && response.data && response.data.success) {
          // 从返回数据中提取百度汉语GIF URL
          const data = response.data.data;
          
          // 检查数据结构是否完整
          if (data && data.detail && data.detail.strokeOrderGif) {
            // 添加时间戳到URL，确保每次都重新加载
            this.updateStrokeGifUrl(data.detail.strokeOrderGif);
            // console.log('成功获取百度汉语GIF URL:', this.strokeGifUrl);
          } else {
            console.error('API返回数据结构不完整:', data);
            this.handleApiError('无法获取汉字笔顺图片，数据结构不完整');
          }
        } else {
          console.error('API请求失败:', response);
          this.handleApiError('请求汉字信息失败');
        }
      } catch (error) {
        console.error('加载汉字笔顺出错:', error);
        this.handleApiError(error.message || '未知错误');
      } finally {
        this.isLoading = false;
      }
    },
    
    // 处理API错误
    handleApiError(message) {
      this.hasError = true;
      uni.showToast({
        title: message,
        icon: 'none',
        duration: 2000
      });
    },
    
    // 更新GIF URL，添加时间戳参数
    updateStrokeGifUrl(baseUrl) {
      if (!baseUrl) {
        console.error('updateStrokeGifUrl: 无效的URL');
        return;
      }
      // 移除旧的时间戳参数（如果有）
      const urlWithoutTimestamp = baseUrl.split('?')[0];
      // 添加新的时间戳参数
      this.strokeGifUrl = `${urlWithoutTimestamp}?t=${this.timestamp}`;
    },
    
    // 处理图片加载错误，最多重试一次
    handleImageError(e) {
      console.error('图片加载错误:', e);
      this.hasError = true;
    },
    
    // 重新加载GIF（重置时间戳强制刷新）
    reloadGif() {
      // 更新时间戳
      this.timestamp = Date.now();
      // 如果已经有URL，直接用时间戳更新即可，不需要重新请求API
      if (this.strokeGifUrl) {
        const baseUrl = this.strokeGifUrl.split('?')[0];
        this.updateStrokeGifUrl(baseUrl);
      } else {
        // 没有URL时才重新请求
        this.loadGif(this.character);
      }
    }
  }
})
</script>

<style>
.hanzi-stroke-container {
  width: 100%;
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 20px;
}

.stroke-image-wrapper {
  width: 300px;
  height: 300px;
  background: #ffffff;
  border-radius: 8px;
  border: 1px solid #dddddd;
  display: flex;
  align-items: center;
  justify-content: center;
  overflow: hidden;
}

.stroke-gif {
  width: 250px;
  height: 250px;
  object-fit: contain;
}

.controls {
  display: flex;
  gap: 15px;
}

.control-btn {
  padding: 8px 15px;
  background-color: #007aff;
  color: white;
  border: none;
  border-radius: 4px;
  margin-bottom: 15px;
  font-size: 14px;
}
</style> 